// 云函数：试卷统计分析
const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

/**
 * 试卷统计分析云函数
 * 
 * 参数：
 * - paperId: 试卷ID(必填)
 * - classId: 班级ID(可选)
 */
exports.main = async (event, context) => {
  const { paperId, classId } = event;
  
  try {
    // 参数校验
    if (!paperId) {
      return {
        success: false,
        message: '请指定试卷ID'
      };
    }
    
    // 1. 获取试卷基本信息
    const paperRes = await db.collection('papers').doc(paperId).get();
    const paper = paperRes.data;
    
    if (!paper) {
      return {
        success: false,
        message: '试卷不存在'
      };
    }
    
    // 2. 构建查询条件
    let match = {
      paperId: paperId,
      status: 'completed'
    };
    
    // 如果指定了班级，则只统计该班级的数据
    if (classId) {
      // 查询班级学生
      const classStudents = await db.collection('users')
        .where({
          classId: classId,
          role: 'student'
        })
        .field({
          _id: true
        })
        .get();
      
      const studentIds = classStudents.data.map(s => s._id);
      
      match.userId = _.in(studentIds);
    }
    
    // 3. 获取答卷记录
    const recordsRes = await db.collection('records')
      .where(match)
      .get();
    
    const records = recordsRes.data;
    
    // 如果没有答卷记录，返回空结果
    if (records.length === 0) {
      return {
        success: true,
        paper,
        statistics: {
          totalStudents: 0,
          participantCount: 0,
          participantRate: 0,
          highestScore: 0,
          lowestScore: 0,
          averageScore: 0,
          medianScore: 0,
          passCount: 0,
          passRate: 0,
          excellentCount: 0,
          excellentRate: 0,
          scoreBands: [],
          questionStatistics: []
        }
      };
    }
    
    // 4. 计算基本统计信息
    let totalStudentsCount = 0;
    
    if (classId) {
      // 获取班级学生总数
      const classStudentsCount = await db.collection('users')
        .where({
          classId: classId,
          role: 'student'
        })
        .count();
      
      totalStudentsCount = classStudentsCount.total;
    } else {
      // 设置为参与人数
      totalStudentsCount = records.length;
    }
    
    // 参与率
    const participantCount = records.length;
    const participantRate = totalStudentsCount > 0 ? (participantCount / totalStudentsCount * 100).toFixed(2) : 0;
    
    // 分数统计
    const scores = records.map(r => r.totalScore || 0);
    const sortedScores = [...scores].sort((a, b) => a - b);
    
    const highestScore = Math.max(...scores);
    const lowestScore = Math.min(...scores);
    const averageScore = (scores.reduce((sum, score) => sum + score, 0) / scores.length).toFixed(2);
    const medianScore = sortedScores.length % 2 === 0 ? 
      (sortedScores[sortedScores.length / 2 - 1] + sortedScores[sortedScores.length / 2]) / 2 : 
      sortedScores[Math.floor(sortedScores.length / 2)];
    
    // 及格与优秀统计（假设60分及格，90分优秀）
    const passCount = scores.filter(score => score >= 60).length;
    const passRate = (passCount / scores.length * 100).toFixed(2);
    const excellentCount = scores.filter(score => score >= 90).length;
    const excellentRate = (excellentCount / scores.length * 100).toFixed(2);
    
    // 分数段分布
    const scoreBands = [
      { band: '0-59', count: 0, ratio: 0 },
      { band: '60-69', count: 0, ratio: 0 },
      { band: '70-79', count: 0, ratio: 0 },
      { band: '80-89', count: 0, ratio: 0 },
      { band: '90-100', count: 0, ratio: 0 }
    ];
    
    scores.forEach(score => {
      if (score < 60) {
        scoreBands[0].count++;
      } else if (score < 70) {
        scoreBands[1].count++;
      } else if (score < 80) {
        scoreBands[2].count++;
      } else if (score < 90) {
        scoreBands[3].count++;
      } else {
        scoreBands[4].count++;
      }
    });
    
    scoreBands.forEach(band => {
      band.ratio = (band.count / scores.length * 100).toFixed(2);
    });
    
    // 5. 计算题目统计信息
    const questionStatistics = [];
    
    // 获取试卷中的所有题目
    if (paper.questions && paper.questions.length > 0) {
      // 为每个题目计算统计数据
      for (const paperQuestion of paper.questions) {
        const questionId = paperQuestion.questionId;
        
        // 收集该题目的所有回答
        const answers = [];
        records.forEach(record => {
          const answer = (record.answers || []).find(a => a.questionId === questionId);
          if (answer) {
            answers.push(answer);
          }
        });
        
        // 计算正确率
        const correctCount = answers.filter(a => a.isCorrect).length;
        const correctRate = answers.length > 0 ? (correctCount / answers.length * 100).toFixed(2) : 0;
        
        // 计算平均得分
        const totalScore = answers.reduce((sum, a) => sum + (a.score || 0), 0);
        const averageQuestionScore = answers.length > 0 ? (totalScore / answers.length).toFixed(2) : 0;
        
        // 计算得分率
        const scoreRate = paperQuestion.score > 0 ? (averageQuestionScore / paperQuestion.score * 100).toFixed(2) : 0;
        
        // 错误答案分布（选择题）
        const wrongAnswers = {};
        const totalWrong = answers.length - correctCount;
        
        answers.forEach(answer => {
          if (!answer.isCorrect && answer.userAnswer) {
            if (!wrongAnswers[answer.userAnswer]) {
              wrongAnswers[answer.userAnswer] = 0;
            }
            wrongAnswers[answer.userAnswer]++;
          }
        });
        
        // 将错误答案分布转换为数组
        const wrongAnswerDistribution = Object.keys(wrongAnswers).map(key => {
          return {
            answer: key,
            count: wrongAnswers[key],
            ratio: totalWrong > 0 ? (wrongAnswers[key] / totalWrong * 100).toFixed(2) : 0
          };
        }).sort((a, b) => b.count - a.count);
        
        // 添加到题目统计数组
        questionStatistics.push({
          questionId,
          type: paperQuestion.type,
          score: paperQuestion.score,
          answersCount: answers.length,
          correctCount,
          correctRate,
          averageScore: averageQuestionScore,
          scoreRate,
          wrongAnswerDistribution
        });
      }
    }
    
    // 6. 构建最终结果
    return {
      success: true,
      paper,
      statistics: {
        totalStudents: totalStudentsCount,
        participantCount,
        participantRate,
        highestScore,
        lowestScore,
        averageScore,
        medianScore,
        passCount,
        passRate,
        excellentCount,
        excellentRate,
        scoreBands,
        questionStatistics
      }
    };
  } catch (error) {
    console.error('试卷统计分析失败:', error);
    return {
      success: false,
      message: '试卷统计分析失败: ' + error.message
    };
  }
}; 